/*
 * MyDownloader.cpp
 *
 *  Created on: Jan 31, 2011
 *      Author: andris_bada
 */

#include "MyDownloader.h"

using namespace Osp::Net::Http;
using namespace Osp::Io;
using namespace Osp::Base;

class MyEventListener :
        public virtual IHttpTransactionEventListener
    {
    public:
	MyEventListener(String path) {myPath = path;}
	~MyEventListener() {}

    protected:
	String myPath;

	void OnTransactionReadyToRead(HttpSession& httpSession, HttpTransaction& httpTransaction, int availableBodyLen)
	{
		HttpResponse* pResponse = httpTransaction.GetResponse();
		NetHttpStatusCode code = pResponse->GetStatusCode();

		if(code!=NET_HTTP_STATUS_OK){
			AppLog("para");
			return;
		}

		ByteBuffer* pBody = pResponse->ReadBodyN();
		File file;
		result r = E_SUCCESS;
		r = file.Construct(myPath, L"w+", true);
		if(IsFailed(r))  {
			AppLog("hiba a file mentesekor");
			return;
		}
		r = file.Write(*pBody);
		file.Flush();
		AppLog("a file sikeresen elmentve");
	}

	void OnTransactionAborted(HttpSession& httpSession, HttpTransaction& httpTransaction, result r){}
	void OnTransactionReadyToWrite(HttpSession& httpSession, HttpTransaction& httpTransaction, int recommendedChunkSize){}
	void OnTransactionHeaderCompleted(HttpSession& httpSession, HttpTransaction& httpTransaction, int headerLen, bool bAuthRequired){}
	void OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& httpTransaction){}
	void OnTransactionCertVerificationRequiredN(HttpSession& httpSession, HttpTransaction& httpTransaction, String* pCert){}
};

MyDownloader::MyDownloader() {
	// TODO Auto-generated constructor stub

}

MyDownloader::~MyDownloader() {
	// TODO Auto-generated destructor stub
}

int
MyDownloader::Download(String url, String path){
	result r = E_SUCCESS;
	HttpSession*  __pSession = new HttpSession();
	r = __pSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null ,url, null);
	if (IsFailed(r))
	{
		AppLog("hiba a httpsession letrehozasakor");
		return r;
	}

	HttpTransaction* __pTransaction = __pSession->OpenTransactionN();
	if (null == __pTransaction)
	{
		AppLog("hiba a tranzakcio megnyitasakor");
		return E_FAILURE;
	}

	r = __pTransaction->AddHttpTransactionListener(*(new MyEventListener(path)));
	if (IsFailed(r))
	{
		AppLog("hiba a letoles kozben");
		return r;
	}
	HttpRequest* pRequest = __pTransaction->GetRequest();
	if(pRequest == null)
	{
		AppLog("hiba a request lekeresekor");
		return E_FAILURE;
	}

	r = pRequest->SetUri(url);
	if(IsFailed(r))
	{
		AppLog("url hiba");
		return r;
	}

	r = pRequest->SetMethod(NET_HTTP_METHOD_GET);
	if(IsFailed(r))
	{
		AppLog("hiba a get method beallitasakor");
		return r;
	}
	r = __pTransaction->Submit();
	if(IsFailed(r))
	{
		AppLog("hiba atranzakcio elkuldesekor");
		return r;
	}
	AppLog("Download finished successfully");
	return r;
}
